using System;
using System.Text;
using System.Data;
using Antu.Core.Services;

namespace Antu.Core.Ajax
{
    /// <summary>
    /// Provides methods to serialize and deserialize a Decimal object.
    /// </summary>
    public class DecimalConverter : AbstractJavascriptConverter
    {
        SerializerService _SerializerService = (SerializerService)ServiceManager.Manager.GetService(typeof(SerializerService));
        /// <summary>
        /// Initializes a new instance of the <see cref="DecimalConverter"/> class.
        /// </summary>
        public DecimalConverter()
            : base()
        {
            serializabletypeslist = new Type[] {
				typeof(Decimal)
			};
            deserializabletypeslist = serializabletypeslist;
        }

        /// <summary>
        /// Converts a .NET object into a JSON string.
        /// </summary>
        /// <param name="o">The object to convert.</param>
        /// <returns>Returns a JSON string.</returns>
        public override string Serialize( object o )
        {
            StringBuilder sb = new StringBuilder();
            Serialize( o , sb );
            return sb.ToString();
        }

        /// <summary>
        /// Serializes the specified o.
        /// </summary>
        /// <param name="o">The o.</param>
        /// <param name="sb">The sb.</param>
        public override void Serialize( object o , StringBuilder sb )
        {
            // this.SerializeValue(Decimal.GetBits(d), sb);

            // The following code is not correct, but while JavaScript cannot
            // handle the decimal value correct we are using double instead.

            _SerializerService.Serialize((Double)((Decimal)o), sb);
        }

        /// <summary>
        /// Converts an IJSONObject into an NET object.
        /// </summary>
        /// <param name="o">The IJSONObject object to convert.</param>
        /// <param name="t"></param>
        /// <returns>Returns a .NET object.</returns>
        public override object Deserialize( IJavascriptObject o , Type t )
        {
            JavascriptNumber n = o as JavascriptNumber;

            if ( n == null )
                throw new NotSupportedException();

            string s = n.Value;

            // TODO: return the default value for this primitive data type
            s = s.Replace( "." , System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator );

            Decimal d = Decimal.Parse( s ,
                System.Globalization.NumberStyles.Currency |
                System.Globalization.NumberStyles.AllowExponent );

            return d;
        }
    }
}
